<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">
<meta name="google-site-verification" content="4b5ChOPlfrWPkfJKVSwbnGC4WDT5fyOTDO62HVBosls">
<meta name="baidu-site-verification" content="iotYLCUzXs">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="python,udsoncan,uds,">





  <link rel="alternate" href="/atom.xml" title="songjiapo" type="application/atom+xml">






<meta name="description" content="12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210">
<meta name="keywords" content="python,udsoncan,uds">
<meta property="og:type" content="article">
<meta property="og:title" content="udsoncan.connections源码">
<meta property="og:url" content="https://songjiapo.com/uds/udsoncan.connections.html">
<meta property="og:site_name" content="songjiapo">
<meta property="og:description" content="12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-11-08T12:50:25.651Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="udsoncan.connections源码">
<meta name="twitter:description" content="12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://songjiapo.com/uds/udsoncan.connections.html">





  <title>udsoncan.connections源码 | songjiapo</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?e07193cab6deb965ead8e1aed3d4744f";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">songjiapo</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description"></h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://songjiapo.com/uds/udsoncan.connections.html">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="song jiapo">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="songjiapo">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">udsoncan.connections源码</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-01-12T11:29:08+08:00">
                2019-01-12
              </time>
            

            

            
          </span>

          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/uds/udsoncan.connections.html#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/uds/udsoncan.connections.html" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br><span class="line">244</span><br><span class="line">245</span><br><span class="line">246</span><br><span class="line">247</span><br><span class="line">248</span><br><span class="line">249</span><br><span class="line">250</span><br><span class="line">251</span><br><span class="line">252</span><br><span class="line">253</span><br><span class="line">254</span><br><span class="line">255</span><br><span class="line">256</span><br><span class="line">257</span><br><span class="line">258</span><br><span class="line">259</span><br><span class="line">260</span><br><span class="line">261</span><br><span class="line">262</span><br><span class="line">263</span><br><span class="line">264</span><br><span class="line">265</span><br><span class="line">266</span><br><span class="line">267</span><br><span class="line">268</span><br><span class="line">269</span><br><span class="line">270</span><br><span class="line">271</span><br><span class="line">272</span><br><span class="line">273</span><br><span class="line">274</span><br><span class="line">275</span><br><span class="line">276</span><br><span class="line">277</span><br><span class="line">278</span><br><span class="line">279</span><br><span class="line">280</span><br><span class="line">281</span><br><span class="line">282</span><br><span class="line">283</span><br><span class="line">284</span><br><span class="line">285</span><br><span class="line">286</span><br><span class="line">287</span><br><span class="line">288</span><br><span class="line">289</span><br><span class="line">290</span><br><span class="line">291</span><br><span class="line">292</span><br><span class="line">293</span><br><span class="line">294</span><br><span class="line">295</span><br><span class="line">296</span><br><span class="line">297</span><br><span class="line">298</span><br><span class="line">299</span><br><span class="line">300</span><br><span class="line">301</span><br><span class="line">302</span><br><span class="line">303</span><br><span class="line">304</span><br><span class="line">305</span><br><span class="line">306</span><br><span class="line">307</span><br><span class="line">308</span><br><span class="line">309</span><br><span class="line">310</span><br><span class="line">311</span><br><span class="line">312</span><br><span class="line">313</span><br><span class="line">314</span><br><span class="line">315</span><br><span class="line">316</span><br><span class="line">317</span><br><span class="line">318</span><br><span class="line">319</span><br><span class="line">320</span><br><span class="line">321</span><br><span class="line">322</span><br><span class="line">323</span><br><span class="line">324</span><br><span class="line">325</span><br><span class="line">326</span><br><span class="line">327</span><br><span class="line">328</span><br><span class="line">329</span><br><span class="line">330</span><br><span class="line">331</span><br><span class="line">332</span><br><span class="line">333</span><br><span class="line">334</span><br><span class="line">335</span><br><span class="line">336</span><br><span class="line">337</span><br><span class="line">338</span><br><span class="line">339</span><br><span class="line">340</span><br><span class="line">341</span><br><span class="line">342</span><br><span class="line">343</span><br><span class="line">344</span><br><span class="line">345</span><br><span class="line">346</span><br><span class="line">347</span><br><span class="line">348</span><br><span class="line">349</span><br><span class="line">350</span><br><span class="line">351</span><br><span class="line">352</span><br><span class="line">353</span><br><span class="line">354</span><br><span class="line">355</span><br><span class="line">356</span><br><span class="line">357</span><br><span class="line">358</span><br><span class="line">359</span><br><span class="line">360</span><br><span class="line">361</span><br><span class="line">362</span><br><span class="line">363</span><br><span class="line">364</span><br><span class="line">365</span><br><span class="line">366</span><br><span class="line">367</span><br><span class="line">368</span><br><span class="line">369</span><br><span class="line">370</span><br><span class="line">371</span><br><span class="line">372</span><br><span class="line">373</span><br><span class="line">374</span><br><span class="line">375</span><br><span class="line">376</span><br><span class="line">377</span><br><span class="line">378</span><br><span class="line">379</span><br><span class="line">380</span><br><span class="line">381</span><br><span class="line">382</span><br><span class="line">383</span><br><span class="line">384</span><br><span class="line">385</span><br><span class="line">386</span><br><span class="line">387</span><br><span class="line">388</span><br><span class="line">389</span><br><span class="line">390</span><br><span class="line">391</span><br><span class="line">392</span><br><span class="line">393</span><br><span class="line">394</span><br><span class="line">395</span><br><span class="line">396</span><br><span class="line">397</span><br><span class="line">398</span><br><span class="line">399</span><br><span class="line">400</span><br><span class="line">401</span><br><span class="line">402</span><br><span class="line">403</span><br><span class="line">404</span><br><span class="line">405</span><br><span class="line">406</span><br><span class="line">407</span><br><span class="line">408</span><br><span class="line">409</span><br><span class="line">410</span><br><span class="line">411</span><br><span class="line">412</span><br><span class="line">413</span><br><span class="line">414</span><br><span class="line">415</span><br><span class="line">416</span><br><span class="line">417</span><br><span class="line">418</span><br><span class="line">419</span><br><span class="line">420</span><br><span class="line">421</span><br><span class="line">422</span><br><span class="line">423</span><br><span class="line">424</span><br><span class="line">425</span><br><span class="line">426</span><br><span class="line">427</span><br><span class="line">428</span><br><span class="line">429</span><br><span class="line">430</span><br><span class="line">431</span><br><span class="line">432</span><br><span class="line">433</span><br><span class="line">434</span><br><span class="line">435</span><br><span class="line">436</span><br><span class="line">437</span><br><span class="line">438</span><br><span class="line">439</span><br><span class="line">440</span><br><span class="line">441</span><br><span class="line">442</span><br><span class="line">443</span><br><span class="line">444</span><br><span class="line">445</span><br><span class="line">446</span><br><span class="line">447</span><br><span class="line">448</span><br><span class="line">449</span><br><span class="line">450</span><br><span class="line">451</span><br><span class="line">452</span><br><span class="line">453</span><br><span class="line">454</span><br><span class="line">455</span><br><span class="line">456</span><br><span class="line">457</span><br><span class="line">458</span><br><span class="line">459</span><br><span class="line">460</span><br><span class="line">461</span><br><span class="line">462</span><br><span class="line">463</span><br><span class="line">464</span><br><span class="line">465</span><br><span class="line">466</span><br><span class="line">467</span><br><span class="line">468</span><br><span class="line">469</span><br><span class="line">470</span><br><span class="line">471</span><br><span class="line">472</span><br><span class="line">473</span><br><span class="line">474</span><br><span class="line">475</span><br><span class="line">476</span><br><span class="line">477</span><br><span class="line">478</span><br><span class="line">479</span><br><span class="line">480</span><br><span class="line">481</span><br><span class="line">482</span><br><span class="line">483</span><br><span class="line">484</span><br><span class="line">485</span><br><span class="line">486</span><br><span class="line">487</span><br><span class="line">488</span><br><span class="line">489</span><br><span class="line">490</span><br><span class="line">491</span><br><span class="line">492</span><br><span class="line">493</span><br><span class="line">494</span><br><span class="line">495</span><br><span class="line">496</span><br><span class="line">497</span><br><span class="line">498</span><br><span class="line">499</span><br><span class="line">500</span><br><span class="line">501</span><br><span class="line">502</span><br><span class="line">503</span><br><span class="line">504</span><br><span class="line">505</span><br><span class="line">506</span><br><span class="line">507</span><br><span class="line">508</span><br><span class="line">509</span><br><span class="line">510</span><br><span class="line">511</span><br><span class="line">512</span><br><span class="line">513</span><br><span class="line">514</span><br><span class="line">515</span><br><span class="line">516</span><br><span class="line">517</span><br><span class="line">518</span><br><span class="line">519</span><br><span class="line">520</span><br><span class="line">521</span><br><span class="line">522</span><br><span class="line">523</span><br><span class="line">524</span><br><span class="line">525</span><br><span class="line">526</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> socket</span><br><span class="line"><span class="keyword">import</span> queue</span><br><span class="line"><span class="keyword">import</span> threading</span><br><span class="line"><span class="keyword">import</span> logging</span><br><span class="line"><span class="keyword">import</span> binascii</span><br><span class="line"><span class="keyword">import</span> sys</span><br><span class="line"><span class="keyword">from</span> abc <span class="keyword">import</span> ABC, abstractmethod</span><br><span class="line"><span class="keyword">import</span> functools</span><br><span class="line"><span class="keyword">import</span> time</span><br><span class="line"></span><br><span class="line"><span class="keyword">try</span>:</span><br><span class="line">	<span class="keyword">import</span> can</span><br><span class="line">	_import_can_err = <span class="keyword">None</span></span><br><span class="line"><span class="keyword">except</span> Exception <span class="keyword">as</span> e:</span><br><span class="line">	_import_can_err = e</span><br><span class="line"></span><br><span class="line"><span class="keyword">try</span>:</span><br><span class="line">	<span class="keyword">import</span> isotp</span><br><span class="line">	_import_isotp_err = <span class="keyword">None</span></span><br><span class="line"><span class="keyword">except</span> Exception <span class="keyword">as</span> e:</span><br><span class="line">	_import_isotp_err = e</span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> udsoncan.Request <span class="keyword">import</span> Request</span><br><span class="line"><span class="keyword">from</span> udsoncan.Response <span class="keyword">import</span> Response</span><br><span class="line"><span class="keyword">from</span> udsoncan.exceptions <span class="keyword">import</span> TimeoutException</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">BaseConnection</span><span class="params">(ABC)</span>:</span></span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, name=None)</span>:</span></span><br><span class="line">		<span class="keyword">if</span> name <span class="keyword">is</span> <span class="keyword">None</span>:</span><br><span class="line">			self.name = <span class="string">'Connection'</span></span><br><span class="line">		<span class="keyword">else</span>:</span><br><span class="line">			self.name = <span class="string">'Connection[%s]'</span> % (name)</span><br><span class="line"></span><br><span class="line">		self.logger = logging.getLogger(self.name)</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">send</span><span class="params">(self, data)</span>:</span></span><br><span class="line">		<span class="string">"""Sends data to the underlying transport protocol</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">		:param data: The data or object to send. If a Request or Response is given, the value returned by get_payload() will be sent.</span></span><br><span class="line"><span class="string">		:type data: bytes, Request, Response</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">		:returns: None</span></span><br><span class="line"><span class="string">		"""</span></span><br><span class="line"></span><br><span class="line">		<span class="keyword">if</span> isinstance(data, Request) <span class="keyword">or</span> isinstance(data, Response):</span><br><span class="line">			payload = data.get_payload()  </span><br><span class="line">		<span class="keyword">else</span> :</span><br><span class="line">			payload = data</span><br><span class="line"></span><br><span class="line">		self.logger.debug(<span class="string">'Sending %d bytes : [%s]'</span> % (len(payload), binascii.hexlify(payload) ))</span><br><span class="line">		self.specific_send(payload)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">wait_frame</span><span class="params">(self, timeout=<span class="number">2</span>, exception=False)</span>:</span></span><br><span class="line">		<span class="string">"""Waits for the reception of a frame of data from the underlying transport protocol</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">		:param timeout: The maximum amount of time to wait before giving up in seconds</span></span><br><span class="line"><span class="string">		:type timeout: int</span></span><br><span class="line"><span class="string">		:param exception: Boolean value indicating if this function may return exceptions.</span></span><br><span class="line"><span class="string">			When ``True``, all exceptions may be raised, including ``TimeoutException``</span></span><br><span class="line"><span class="string">			When ``False``, all exceptions will be logged as ``DEBUG`` and ``None`` will be returned.</span></span><br><span class="line"><span class="string">		:type exception: bool</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">		:returns: Received data</span></span><br><span class="line"><span class="string">		:rtype: bytes or None</span></span><br><span class="line"><span class="string">		"""</span></span><br><span class="line">		<span class="keyword">try</span>:</span><br><span class="line">			frame = self.specific_wait_frame(timeout=timeout)</span><br><span class="line">		<span class="keyword">except</span> Exception <span class="keyword">as</span> e:</span><br><span class="line">			self.logger.debug(<span class="string">'No data received: [%s] - %s '</span> % (e.__class__.__name__, str(e)))</span><br><span class="line"></span><br><span class="line">			<span class="keyword">if</span> exception == <span class="keyword">True</span>:</span><br><span class="line">				<span class="keyword">raise</span></span><br><span class="line">			<span class="keyword">else</span>:</span><br><span class="line">				frame = <span class="keyword">None</span></span><br><span class="line"></span><br><span class="line">		<span class="keyword">if</span> frame <span class="keyword">is</span> <span class="keyword">not</span> <span class="keyword">None</span>:</span><br><span class="line">			self.logger.debug(<span class="string">'Received %d bytes : [%s]'</span> % (len(frame), binascii.hexlify(frame) ))</span><br><span class="line">		<span class="keyword">return</span> frame</span><br><span class="line"></span><br><span class="line">	</span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">__enter__</span><span class="params">(self)</span>:</span></span><br><span class="line">		<span class="keyword">return</span> self</span><br><span class="line"></span><br><span class="line"><span class="meta">	@abstractmethod</span></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">specific_send</span><span class="params">(self, payload)</span>:</span></span><br><span class="line">		<span class="string">"""The implementation of the send method.</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">		:param payload: Data to send</span></span><br><span class="line"><span class="string">		:type payload: bytes</span></span><br><span class="line"><span class="string">		</span></span><br><span class="line"><span class="string">		:returns: None</span></span><br><span class="line"><span class="string">		"""</span></span><br><span class="line">		<span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">	@abstractmethod</span></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">specific_wait_frame</span><span class="params">(self, timeout=<span class="number">2</span>)</span>:</span></span><br><span class="line">		<span class="string">"""The implementation of the ``wait_frame`` method. </span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">		:param timeout: The maximum amount of time to wait before giving up</span></span><br><span class="line"><span class="string">		:type timeout: int</span></span><br><span class="line"><span class="string">		</span></span><br><span class="line"><span class="string">		:returns: Received data</span></span><br><span class="line"><span class="string">		:rtype: bytes or None</span></span><br><span class="line"><span class="string">		"""</span></span><br><span class="line">		<span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">	@abstractmethod</span></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">open</span><span class="params">(self)</span>:</span></span><br><span class="line">		<span class="string">""" Set up the connection object. </span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">		:returns: None</span></span><br><span class="line"><span class="string">		"""</span></span><br><span class="line">		<span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">	@abstractmethod</span></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">close</span><span class="params">(self)</span>:</span></span><br><span class="line">		<span class="string">""" Close the connection object</span></span><br><span class="line"><span class="string">		</span></span><br><span class="line"><span class="string">		:returns: None</span></span><br><span class="line"><span class="string">		"""</span></span><br><span class="line">		<span class="keyword">pass</span>	</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">	@abstractmethod</span></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">empty_rxqueue</span><span class="params">(self)</span>:</span></span><br><span class="line">		<span class="string">""" Empty all unread data in the reception buffer.</span></span><br><span class="line"><span class="string">		</span></span><br><span class="line"><span class="string">		:returns: None</span></span><br><span class="line"><span class="string">		"""</span></span><br><span class="line">		<span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line">	</span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">__exit__</span><span class="params">(self, type, value, traceback)</span>:</span></span><br><span class="line">		<span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">SocketConnection</span><span class="params">(BaseConnection)</span>:</span></span><br><span class="line">	<span class="string">"""</span></span><br><span class="line"><span class="string">	Sends and receives data through a socket.</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">	:param sock: The socket to use. This socket must be bound and ready to use. Only ``send()`` and ``recv()`` will be called by this Connection</span></span><br><span class="line"><span class="string">	:type sock: socket.socket</span></span><br><span class="line"><span class="string">	:param bufsize: Maximum buffer size of the socket, this value is passed to ``recv()``</span></span><br><span class="line"><span class="string">	:type bufsize: int</span></span><br><span class="line"><span class="string">	:param name: This name is included in the logger name so that its output can be redirected. The logger name will be ``Connection[&lt;name&gt;]``</span></span><br><span class="line"><span class="string">	:type name: string</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">	"""</span></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, sock, bufsize=<span class="number">4095</span>, name=None)</span>:</span></span><br><span class="line">		BaseConnection.__init__(self, name)</span><br><span class="line"></span><br><span class="line">		self.rxqueue = queue.Queue()</span><br><span class="line">		self.exit_requested = <span class="keyword">False</span></span><br><span class="line">		self.opened = <span class="keyword">False</span></span><br><span class="line">		self.rxthread = <span class="keyword">None</span></span><br><span class="line">		self.sock = sock</span><br><span class="line">		self.sock.settimeout(<span class="number">0.1</span>)	<span class="comment"># for recv</span></span><br><span class="line">		self.bufsize=bufsize</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">open</span><span class="params">(self)</span>:</span></span><br><span class="line">		self.exit_requested = <span class="keyword">False</span></span><br><span class="line">		self.rxthread = threading.Thread(target=self.rxthread_task)</span><br><span class="line">		self.rxthread.start()</span><br><span class="line">		self.opened = <span class="keyword">True</span></span><br><span class="line">		self.logger.info(<span class="string">'Connection opened'</span>)</span><br><span class="line">		<span class="keyword">return</span> self</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">__enter__</span><span class="params">(self)</span>:</span></span><br><span class="line">		<span class="keyword">return</span> self</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">__exit__</span><span class="params">(self, type, value, traceback)</span>:</span></span><br><span class="line">		self.close()</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">is_open</span><span class="params">(self)</span>:</span></span><br><span class="line">		<span class="keyword">return</span> self.opened</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">rxthread_task</span><span class="params">(self)</span>:</span></span><br><span class="line">		<span class="keyword">while</span> <span class="keyword">not</span> self.exit_requested:</span><br><span class="line">			<span class="keyword">try</span>:</span><br><span class="line">				data = self.sock.recv(self.bufsize)</span><br><span class="line">				<span class="keyword">if</span> data <span class="keyword">is</span> <span class="keyword">not</span> <span class="keyword">None</span>:</span><br><span class="line">					self.rxqueue.put(data)</span><br><span class="line">			<span class="keyword">except</span> socket.timeout:</span><br><span class="line">				<span class="keyword">pass</span></span><br><span class="line">			<span class="keyword">except</span> Exception:</span><br><span class="line">				self.exit_requested = <span class="keyword">True</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">close</span><span class="params">(self)</span>:</span></span><br><span class="line">		self.exit_requested = <span class="keyword">True</span></span><br><span class="line">		self.rxthread.join()</span><br><span class="line">		self.opened = <span class="keyword">False</span></span><br><span class="line">		self.logger.info(<span class="string">'Connection closed'</span>)</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">specific_send</span><span class="params">(self, payload)</span>:</span></span><br><span class="line">		self.sock.send(payload)</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">specific_wait_frame</span><span class="params">(self, timeout=<span class="number">2</span>)</span>:</span></span><br><span class="line">		<span class="keyword">if</span> <span class="keyword">not</span> self.opened:</span><br><span class="line">			<span class="keyword">raise</span> RuntimeError(<span class="string">"Connection is not open"</span>)</span><br><span class="line"></span><br><span class="line">		timedout = <span class="keyword">False</span></span><br><span class="line">		frame = <span class="keyword">None</span></span><br><span class="line">		<span class="keyword">try</span>:</span><br><span class="line">			frame = self.rxqueue.get(block=<span class="keyword">True</span>, timeout=timeout)</span><br><span class="line"></span><br><span class="line">		<span class="keyword">except</span> queue.Empty:</span><br><span class="line">			timedout = <span class="keyword">True</span></span><br><span class="line">			</span><br><span class="line">		<span class="keyword">if</span> timedout:</span><br><span class="line">			<span class="keyword">raise</span> TimeoutException(<span class="string">"Did not received frame in time (timeout=%s sec)"</span> % timeout)</span><br><span class="line"></span><br><span class="line">		<span class="keyword">return</span> frame</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">empty_rxqueue</span><span class="params">(self)</span>:</span></span><br><span class="line">		<span class="keyword">while</span> <span class="keyword">not</span> self.rxqueue.empty():</span><br><span class="line">			self.rxqueue.get()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">IsoTPSocketConnection</span><span class="params">(BaseConnection)</span>:</span></span><br><span class="line">	<span class="string">"""</span></span><br><span class="line"><span class="string">	Sends and receives data through an ISO-TP socket. Makes cleaner code than SocketConnection but offers no additional functionality.</span></span><br><span class="line"><span class="string">	The `can-isotp module &lt;https://github.com/pylessard/python-can-isotp&gt;`_ must be installed in order to use this connection</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">	:param interface: The can interface to use (example: `can0`)</span></span><br><span class="line"><span class="string">	:type interface: string</span></span><br><span class="line"><span class="string">	:param rxid: The reception CAN id</span></span><br><span class="line"><span class="string">	:type rxid: int </span></span><br><span class="line"><span class="string">	:param txid: The transmission CAN id</span></span><br><span class="line"><span class="string">	:type txid: int</span></span><br><span class="line"><span class="string">	:param name: This name is included in the logger name so that its output can be redirected. The logger name will be ``Connection[&lt;name&gt;]``</span></span><br><span class="line"><span class="string">	:type name: string</span></span><br><span class="line"><span class="string">	:param tpsock: An optional ISO-TP socket to use instead of creating one.</span></span><br><span class="line"><span class="string">	:type tpsock: isotp.socket</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">	"""</span></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, interface, rxid, txid, name=None, tpsock=None)</span>:</span></span><br><span class="line">		</span><br><span class="line">		BaseConnection.__init__(self, name)</span><br><span class="line"></span><br><span class="line">		self.interface=interface</span><br><span class="line">		self.rxid=rxid</span><br><span class="line">		self.txid=txid</span><br><span class="line">		self.rxqueue = queue.Queue()</span><br><span class="line">		self.exit_requested = <span class="keyword">False</span></span><br><span class="line">		self.opened = <span class="keyword">False</span></span><br><span class="line"></span><br><span class="line">		<span class="keyword">if</span> tpsock <span class="keyword">is</span> <span class="keyword">None</span>:</span><br><span class="line">			<span class="keyword">if</span> <span class="string">'isotp'</span> <span class="keyword">not</span> <span class="keyword">in</span> sys.modules:</span><br><span class="line">				<span class="keyword">if</span> _import_isotp_err <span class="keyword">is</span> <span class="keyword">None</span>:</span><br><span class="line">					<span class="keyword">raise</span> ImportError(<span class="string">'isotp module is not loaded'</span>)</span><br><span class="line">				<span class="keyword">else</span>:</span><br><span class="line">					<span class="keyword">raise</span> _import_isotp_err</span><br><span class="line">			self.tpsock = isotp.socket(timeout=<span class="number">0.1</span>)</span><br><span class="line">		<span class="keyword">else</span>:</span><br><span class="line">			self.tpsock = tpsock</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">open</span><span class="params">(self)</span>:</span></span><br><span class="line">		self.tpsock.bind(self.interface, rxid=self.rxid, txid=self.txid)</span><br><span class="line">		self.exit_requested = <span class="keyword">False</span></span><br><span class="line">		self.rxthread = threading.Thread(target=self.rxthread_task)</span><br><span class="line">		self.rxthread.start()</span><br><span class="line">		self.opened = <span class="keyword">True</span></span><br><span class="line">		self.logger.info(<span class="string">'Connection opened'</span>)</span><br><span class="line">		<span class="keyword">return</span> self</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">__enter__</span><span class="params">(self)</span>:</span></span><br><span class="line">		<span class="keyword">return</span> self</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">__exit__</span><span class="params">(self, type, value, traceback)</span>:</span></span><br><span class="line">		self.close()</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">is_open</span><span class="params">(self)</span>:</span></span><br><span class="line">		<span class="keyword">return</span> self.tpsock.bound</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">rxthread_task</span><span class="params">(self)</span>:</span></span><br><span class="line">		<span class="keyword">while</span> <span class="keyword">not</span> self.exit_requested:</span><br><span class="line">			<span class="keyword">try</span>:</span><br><span class="line">				data = self.tpsock.recv()</span><br><span class="line">				<span class="keyword">if</span> data <span class="keyword">is</span> <span class="keyword">not</span> <span class="keyword">None</span>:</span><br><span class="line">					self.rxqueue.put(data)</span><br><span class="line">			<span class="keyword">except</span> socket.timeout:</span><br><span class="line">				<span class="keyword">pass</span></span><br><span class="line">			<span class="keyword">except</span> Exception:</span><br><span class="line">				self.exit_requested = <span class="keyword">True</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">close</span><span class="params">(self)</span>:</span></span><br><span class="line">		self.exit_requested = <span class="keyword">True</span></span><br><span class="line">		self.rxthread.join()</span><br><span class="line">		self.tpsock.close()</span><br><span class="line">		self.opened = <span class="keyword">False</span></span><br><span class="line">		self.logger.info(<span class="string">'Connection closed'</span>)</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">specific_send</span><span class="params">(self, payload)</span>:</span></span><br><span class="line">		self.tpsock.send(payload)</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">specific_wait_frame</span><span class="params">(self, timeout=<span class="number">2</span>)</span>:</span></span><br><span class="line">		<span class="keyword">if</span> <span class="keyword">not</span> self.opened:</span><br><span class="line">			<span class="keyword">raise</span> RuntimeError(<span class="string">"Connection is not open"</span>)</span><br><span class="line"></span><br><span class="line">		timedout = <span class="keyword">False</span></span><br><span class="line">		frame = <span class="keyword">None</span></span><br><span class="line">		<span class="keyword">try</span>:</span><br><span class="line">			frame = self.rxqueue.get(block=<span class="keyword">True</span>, timeout=timeout)</span><br><span class="line"></span><br><span class="line">		<span class="keyword">except</span> queue.Empty:</span><br><span class="line">			timedout = <span class="keyword">True</span></span><br><span class="line">			</span><br><span class="line">		<span class="keyword">if</span> timedout:</span><br><span class="line">			<span class="keyword">raise</span> TimeoutException(<span class="string">"Did not received ISOTP frame in time (timeout=%s sec)"</span> % timeout)</span><br><span class="line"></span><br><span class="line">		<span class="keyword">return</span> frame</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">empty_rxqueue</span><span class="params">(self)</span>:</span></span><br><span class="line">		<span class="keyword">while</span> <span class="keyword">not</span> self.rxqueue.empty():</span><br><span class="line">			self.rxqueue.get()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">IsoTPConnection</span><span class="params">(IsoTPSocketConnection)</span>:</span></span><br><span class="line">	<span class="string">"""</span></span><br><span class="line"><span class="string">	Same as :class:`IsoTPSocketConnection &lt;udsoncan.connections.IsoTPSocketConnection.Session&gt;`. Exists only for backward compatibility. </span></span><br><span class="line"><span class="string">	"""</span></span><br><span class="line">	<span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">QueueConnection</span><span class="params">(BaseConnection)</span>:</span></span><br><span class="line">	<span class="string">"""</span></span><br><span class="line"><span class="string">	Sends and receives data using 2 Python native queues.</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">	- ``MyConnection.fromuserqueue`` : Data read from this queue when ``wait_frame`` is called</span></span><br><span class="line"><span class="string">	- ``MyConnection.touserqueue`` : Data written to this queue when ``send`` is called</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">	:param mtu: Optional maximum frame size. Messages will be truncated to this size</span></span><br><span class="line"><span class="string">	:type mtu: int</span></span><br><span class="line"><span class="string">	:param name: This name is included in the logger name so that its output can be redirected. The logger name will be ``Connection[&lt;name&gt;]``</span></span><br><span class="line"><span class="string">	:type name: string</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">	"""</span></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, name=None, mtu=<span class="number">4095</span>)</span>:</span></span><br><span class="line">		BaseConnection.__init__(self, name)</span><br><span class="line"></span><br><span class="line">		self.fromuserqueue = queue.Queue()	<span class="comment"># Client reads from this queue. Other end is simulated</span></span><br><span class="line">		self.touserqueue = queue.Queue()	<span class="comment"># Client writes to this queue. Other end is simulated</span></span><br><span class="line">		self.opened = <span class="keyword">False</span></span><br><span class="line">		self.mtu = mtu</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">open</span><span class="params">(self)</span>:</span></span><br><span class="line">		self.opened = <span class="keyword">True</span></span><br><span class="line">		self.logger.info(<span class="string">'Connection opened'</span>)</span><br><span class="line">		<span class="keyword">return</span> self</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">__enter__</span><span class="params">(self)</span>:</span></span><br><span class="line">		<span class="keyword">return</span> self</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">__exit__</span><span class="params">(self, type, value, traceback)</span>:</span></span><br><span class="line">		self.close()</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">is_open</span><span class="params">(self)</span>:</span></span><br><span class="line">		<span class="keyword">return</span> self.opened </span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">close</span><span class="params">(self)</span>:</span></span><br><span class="line">		self.empty_rxqueue()</span><br><span class="line">		self.empty_txqueue()</span><br><span class="line">		self.opened = <span class="keyword">False</span></span><br><span class="line">		self.logger.info(<span class="string">'Connection closed'</span>)	</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">specific_send</span><span class="params">(self, payload)</span>:</span></span><br><span class="line">		<span class="keyword">if</span> self.mtu <span class="keyword">is</span> <span class="keyword">not</span> <span class="keyword">None</span>:</span><br><span class="line">			<span class="keyword">if</span> len(payload) &gt; self.mtu:</span><br><span class="line">				self.logger.warning(<span class="string">"Truncating payload to be set to a length of %d"</span> % (self.mtu))</span><br><span class="line">				payload = payload[<span class="number">0</span>:self.mtu]</span><br><span class="line"></span><br><span class="line">		self.touserqueue.put(payload)</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">specific_wait_frame</span><span class="params">(self, timeout=<span class="number">2</span>)</span>:</span></span><br><span class="line">		<span class="keyword">if</span> <span class="keyword">not</span> self.opened:</span><br><span class="line">			<span class="keyword">raise</span> RuntimeException(<span class="string">"Connection is not open"</span>)</span><br><span class="line"></span><br><span class="line">		timedout = <span class="keyword">False</span></span><br><span class="line">		frame = <span class="keyword">None</span></span><br><span class="line">		<span class="keyword">try</span>:</span><br><span class="line">			frame = self.fromuserqueue.get(block=<span class="keyword">True</span>, timeout=timeout)</span><br><span class="line">		<span class="keyword">except</span> queue.Empty:</span><br><span class="line">			timedout = <span class="keyword">True</span></span><br><span class="line">			</span><br><span class="line">		<span class="keyword">if</span> timedout:</span><br><span class="line">			<span class="keyword">raise</span> TimeoutException(<span class="string">"Did not receive frame from user queue in time (timeout=%s sec)"</span> % timeout)</span><br><span class="line">		</span><br><span class="line">		<span class="keyword">if</span> self.mtu <span class="keyword">is</span> <span class="keyword">not</span> <span class="keyword">None</span>:</span><br><span class="line">			<span class="keyword">if</span> frame <span class="keyword">is</span> <span class="keyword">not</span> <span class="keyword">None</span> <span class="keyword">and</span> len(frame) &gt; self.mtu:</span><br><span class="line">				self.logger.warning(<span class="string">"Truncating received payload to a length of %d"</span> % (self.mtu))</span><br><span class="line">				frame = frame[<span class="number">0</span>:self.mtu]</span><br><span class="line"></span><br><span class="line">		<span class="keyword">return</span> frame</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">empty_rxqueue</span><span class="params">(self)</span>:</span></span><br><span class="line">		<span class="keyword">while</span> <span class="keyword">not</span> self.fromuserqueue.empty():</span><br><span class="line">			self.fromuserqueue.get()</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">empty_txqueue</span><span class="params">(self)</span>:</span></span><br><span class="line">		<span class="keyword">while</span> <span class="keyword">not</span> self.touserqueue.empty():</span><br><span class="line">			self.touserqueue.get()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">PythonIsoTpConnection</span><span class="params">(BaseConnection)</span>:</span></span><br><span class="line">	<span class="string">"""</span></span><br><span class="line"><span class="string">	Sends and receives data using a `can-isotp &lt;https://github.com/pylessard/python-can-isotp&gt;`_ Python module which is a Python implementation of the IsoTp transport protocol</span></span><br><span class="line"><span class="string">	which can be coupled with `python-can &lt;https://python-can.readthedocs.io&gt;`_ module to interract with CAN hardware</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">	`can-isotp &lt;https://github.com/pylessard/python-can-isotp&gt;`_ must be installed in order to use this connection.</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">	See an :ref:`example&lt;example_using_python_can&gt;`</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">	:param isotp_layer: The IsoTP Transport layer object coming from the ``isotp`` module.</span></span><br><span class="line"><span class="string">	:type isotp_layer: :class:`isotp.TransportLayer&lt;isotp.TransportLayer&gt;`</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">	:param name: This name is included in the logger name so that its output can be redirected. The logger name will be ``Connection[&lt;name&gt;]``</span></span><br><span class="line"><span class="string">	:type name: string</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">	"""</span></span><br><span class="line">	mtu = <span class="number">4095</span></span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, isotp_layer, name=None)</span>:</span></span><br><span class="line">		BaseConnection.__init__(self, name)</span><br><span class="line">		self.toIsoTPQueue = queue.Queue()</span><br><span class="line">		self.fromIsoTPQueue = queue.Queue()	</span><br><span class="line">		self.rxthread = <span class="keyword">None</span></span><br><span class="line">		self.exit_requested = <span class="keyword">False</span></span><br><span class="line">		self.opened = <span class="keyword">False</span></span><br><span class="line">		self.isotp_layer = isotp_layer</span><br><span class="line"></span><br><span class="line">		<span class="keyword">assert</span> isinstance(self.isotp_layer, isotp.TransportLayer) , <span class="string">'isotp_layer must be a valid isotp.TransportLayer '</span></span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">open</span><span class="params">(self, bus=None)</span>:</span></span><br><span class="line">		<span class="keyword">if</span> bus <span class="keyword">is</span> <span class="keyword">not</span> <span class="keyword">None</span>:</span><br><span class="line">			self.isotp_layer.set_bus(bus)</span><br><span class="line"></span><br><span class="line">		self.exit_requested = <span class="keyword">False</span></span><br><span class="line">		self.rxthread = threading.Thread(target=self.rxthread_task)</span><br><span class="line">		self.rxthread.start()</span><br><span class="line">		self.opened = <span class="keyword">True</span></span><br><span class="line">		self.logger.info(<span class="string">'Connection opened'</span>)</span><br><span class="line">		<span class="keyword">return</span> self</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">__enter__</span><span class="params">(self)</span>:</span></span><br><span class="line">		<span class="keyword">return</span> self</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">__exit__</span><span class="params">(self, type, value, traceback)</span>:</span></span><br><span class="line">		self.close()</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">is_open</span><span class="params">(self)</span>:</span></span><br><span class="line">		<span class="keyword">return</span> self.opened </span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">close</span><span class="params">(self)</span>:</span></span><br><span class="line">		self.empty_rxqueue()</span><br><span class="line">		self.empty_txqueue()</span><br><span class="line">		self.exit_requested=<span class="keyword">True</span></span><br><span class="line">		self.rxthread.join()</span><br><span class="line">		self.isotp_layer.reset()</span><br><span class="line">		self.opened = <span class="keyword">False</span></span><br><span class="line">		self.logger.info(<span class="string">'Connection closed'</span>)	</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">specific_send</span><span class="params">(self, payload)</span>:</span></span><br><span class="line">		<span class="keyword">if</span> self.mtu <span class="keyword">is</span> <span class="keyword">not</span> <span class="keyword">None</span>:</span><br><span class="line">			<span class="keyword">if</span> len(payload) &gt; self.mtu:</span><br><span class="line">				self.logger.warning(<span class="string">"Truncating payload to be set to a length of %d"</span> % (self.mtu))</span><br><span class="line">				payload = payload[<span class="number">0</span>:self.mtu]</span><br><span class="line"></span><br><span class="line">		self.toIsoTPQueue.put(bytearray(payload)) <span class="comment"># isotp.protocol.TransportLayer uses byte array. udsoncan is strict on bytes format</span></span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">specific_wait_frame</span><span class="params">(self, timeout=<span class="number">2</span>)</span>:</span></span><br><span class="line">		<span class="keyword">if</span> <span class="keyword">not</span> self.opened:</span><br><span class="line">			<span class="keyword">raise</span> RuntimeException(<span class="string">"Connection is not open"</span>)</span><br><span class="line"></span><br><span class="line">		timedout = <span class="keyword">False</span></span><br><span class="line">		frame = <span class="keyword">None</span></span><br><span class="line">		<span class="keyword">try</span>:</span><br><span class="line">			frame = self.fromIsoTPQueue.get(block=<span class="keyword">True</span>, timeout=timeout)</span><br><span class="line">		<span class="keyword">except</span> queue.Empty:</span><br><span class="line">			timedout = <span class="keyword">True</span></span><br><span class="line">			</span><br><span class="line">		<span class="keyword">if</span> timedout:</span><br><span class="line">			<span class="keyword">raise</span> TimeoutException(<span class="string">"Did not receive frame from user queue in time (timeout=%s sec)"</span> % timeout)</span><br><span class="line">		</span><br><span class="line">		<span class="keyword">if</span> self.mtu <span class="keyword">is</span> <span class="keyword">not</span> <span class="keyword">None</span>:</span><br><span class="line">			<span class="keyword">if</span> frame <span class="keyword">is</span> <span class="keyword">not</span> <span class="keyword">None</span> <span class="keyword">and</span> len(frame) &gt; self.mtu:</span><br><span class="line">				self.logger.warning(<span class="string">"Truncating received payload to a length of %d"</span> % (self.mtu))</span><br><span class="line">				frame = frame[<span class="number">0</span>:self.mtu]</span><br><span class="line"></span><br><span class="line">		<span class="keyword">return</span> bytes(frame)	<span class="comment"># isotp.protocol.TransportLayer uses bytearray. udsoncan is strict on bytes format</span></span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">empty_rxqueue</span><span class="params">(self)</span>:</span></span><br><span class="line">		<span class="keyword">while</span> <span class="keyword">not</span> self.fromIsoTPQueue.empty():</span><br><span class="line">			self.fromIsoTPQueue.get()</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">empty_txqueue</span><span class="params">(self)</span>:</span></span><br><span class="line">		<span class="keyword">while</span> <span class="keyword">not</span> self.toIsoTPQueue.empty():</span><br><span class="line">			self.toIsoTPQueue.get()			</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">rxthread_task</span><span class="params">(self)</span>:</span></span><br><span class="line">		<span class="keyword">while</span> <span class="keyword">not</span> self.exit_requested:</span><br><span class="line">			<span class="keyword">try</span>:</span><br><span class="line">				<span class="keyword">while</span> <span class="keyword">not</span> self.toIsoTPQueue.empty():</span><br><span class="line">					self.isotp_layer.send(self.toIsoTPQueue.get())</span><br><span class="line"></span><br><span class="line">				self.isotp_layer.process()</span><br><span class="line">				</span><br><span class="line">				<span class="keyword">while</span> self.isotp_layer.available():</span><br><span class="line">					self.fromIsoTPQueue.put(self.isotp_layer.recv())</span><br><span class="line"></span><br><span class="line">				time.sleep(self.isotp_layer.sleep_time())</span><br><span class="line"></span><br><span class="line">			<span class="keyword">except</span> Exception <span class="keyword">as</span> e:</span><br><span class="line">				self.exit_requested = <span class="keyword">True</span></span><br><span class="line">				self.logger.error(str(e))</span><br></pre></td></tr></table></figure>
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/python/" rel="tag"># python</a>
          
            <a href="/tags/udsoncan/" rel="tag"># udsoncan</a>
          
            <a href="/tags/uds/" rel="tag"># uds</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/uds/udsoncan.html" rel="next" title="udsoncan-underlying protocol(connections)">
                <i class="fa fa-chevron-left"></i> udsoncan-underlying protocol(connections)
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/uds/Request and Response.html" rel="prev" title="请求与应答">
                请求与应答 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">song jiapo</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">57</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/songapore" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:291946540@qq.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 &mdash; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">song jiapo</span>

  
</div>









        







        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: 'l1gitUPNjT1yErmRT7fmIUb3-gzGzoHsz',
        appKey: 'cJ2gj9m4cWlnD3Yw8VBXz3pw',
        placeholder: 'Just go go',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  
  


  

  

</body>
</html>
